# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10005164': {  # dwc 支付宝3%（10---5000）D0结算
        'API_KEY': '8314c46944d649c09661f4e5a225f6a8',
        'gateway': 'https://rpi.tongyu-pay.com/unifiedorder',
        'query_gateway': 'https://rpi.tongyu-pay.com/orderquery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = 'biz_content' + '=' + str(parameter) + '&key=' + str(key)
    _LOGGER.info("tongyupay sign str: %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_pay_sign(parameter, key):
    data = parameter['biz_content']
    s = 'biz_content' + '=' + str(data) + '&key=' + str(key)
    _LOGGER.info("tongyupay sign str: %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_query_sign(parameter, key):
    s = 'biz_content' + '=' + parameter + '&key=' + str(key)
    _LOGGER.info("tongyupay sign str: %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(sign, data, key):
    params = _get_str(data, ',"biz_content":', '}}') + '}'
    calculated_sign = generate_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("tongyupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_notify_sign(sign, data, key):
    params = _get_str(data, ',"biz_content":', '}}') + '}'
    calculated_sign = generate_query_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("tongyupay query sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_platform(service):
    if service == 'alipay':
        return 'ALIPAY'


def _get_pay_type(service):
    if service == 'alipay':
        return 'MWEB'


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    dct = dict(
        version='1.0',
        mch_id=app_id,
        out_order_no=str(pay.id),
        pay_platform=_get_pay_platform(service),
        pay_type=_get_pay_type(service),
        payment_fee=str(int(pay_amount * 100)),
        cur_type='CNY',
        body='charge',
        notify_url='{}/pay/api/{}/tongyupay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id),
        bill_create_ip=_get_device_ip(info),
    )
    dct_sort = OrderedDict(sorted(dct.items(), key=lambda t: t[0]))
    parameter_dict = OrderedDict((
        ('sign_type', 'MD5'),
        ('biz_content', json.dumps(dct_sort, separators=(',', ':')))
    ))
    parameter_dict['signature'] = generate_pay_sign(parameter_dict, api_key)
    _LOGGER.info("tongyupay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("tongyupay create rsp : %s", response.text)
    return {'charge_info': json.loads(response.text)['biz_content']['mweb_url']}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("tongyupay notify data: %s", request.body)
    verify_notify_sign(data['signature'], request.body, api_key)
    pay_id = data['biz_content']['out_order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('tongyupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'SUCCESS'
    trade_mch_id = data['biz_content']['mch_id']
    trade_no = data['biz_content']['order_no']
    total_fee = float(data['biz_content']['payment_fee']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    # 1：成功；0：失败
    if trade_status == 'SUCCESS' and trade_mch_id == str(app_id):
        _LOGGER.info('tongyupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    data = dict(mch_id=app_id, out_order_no=str(pay_id))
    parameter_dict = OrderedDict((
        ('sign_type', 'MD5'),
        ('biz_content', json.dumps(data))
    ))
    parameter_dict['signature'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info('tongyupay query data, %s', json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('tongyupay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        verify_query_notify_sign(data['signature'], response.text, api_key)
        mch_id = pay_order.mch_id
        trade_status = str(data['ret_code'])
        total_fee = float(data['biz_content']['lists'][0]['payment_fee']) / 100.0
        trade_no = str(data['biz_content']['lists'][0]['order_no'])

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '0':  # 0 表示成功，其他表示失败

            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('tongyupay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
